#!/bin/bash
# 民法典H5应用 - 服务器环境初始化脚本
# 服务器IP: 124.220.227.52
# 适用于 Ubuntu 20.04/22.04

set -e  # 遇到错误立即退出

echo "======================================"
echo "  民法典H5应用 - 服务器环境初始化"
echo "  服务器: 124.220.227.52"
echo "======================================"
echo ""

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

# 1. 更新系统包
echo -e "${YELLOW}[1/7] 更新系统包...${NC}"
sudo apt update && sudo apt upgrade -y

# 2. 安装Python 3.9+和开发工具
echo -e "\n${YELLOW}[2/7] 安装Python 3.9+...${NC}"
sudo apt install -y python3 python3-pip python3-venv python3-dev build-essential
python3 --version

# 3. 安装Node.js 18+
echo -e "\n${YELLOW}[3/7] 安装Node.js 18+...${NC}"
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
node --version
npm --version

# 4. 安装MongoDB
echo -e "\n${YELLOW}[4/7] 安装MongoDB...${NC}"

# 导入MongoDB GPG密钥
curl -fsSL https://www.mongodb.org/static/pgp/server-6.0.asc | \
    sudo gpg -o /usr/share/keyrings/mongodb-server-6.0.gpg --dearmor

# 添加MongoDB仓库
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-6.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse" | \
    sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list

sudo apt update
sudo apt install -y mongodb-org

# 启动MongoDB
sudo systemctl start mongod
sudo systemctl enable mongod

echo -e "${GREEN}MongoDB安装完成${NC}"
mongod --version | head -n 1

# 5. 安装Nginx
echo -e "\n${YELLOW}[5/7] 安装Nginx...${NC}"
sudo apt install -y nginx
sudo systemctl start nginx
sudo systemctl enable nginx
nginx -v

# 6. 安装Supervisor
echo -e "\n${YELLOW}[6/7] 安装Supervisor...${NC}"
sudo apt install -y supervisor
sudo systemctl start supervisor
sudo systemctl enable supervisor
supervisorctl version

# 7. 创建项目目录和设置权限
echo -e "\n${YELLOW}[7/7] 创建项目目录...${NC}"
mkdir -p /home/ubuntu/civil/logs
chmod 755 /home/ubuntu/civil

echo -e "${GREEN}目录创建完成${NC}"

# 安装完成总结
echo ""
echo -e "${GREEN}======================================"
echo "  ✅ 服务器环境初始化完成！"
echo "======================================"
echo ""
echo "已安装的服务："
echo "  ✓ Python: $(python3 --version)"
echo "  ✓ Node.js: $(node --version)"
echo "  ✓ NPM: $(npm --version)"
echo "  ✓ MongoDB: $(mongod --version | head -n 1)"
echo "  ✓ Nginx: $(nginx -v 2>&1)"
echo "  ✓ Supervisor: $(supervisorctl version)"
echo ""
echo "服务状态："
echo "  ✓ MongoDB: $(systemctl is-active mongod)"
echo "  ✓ Nginx: $(systemctl is-active nginx)"
echo "  ✓ Supervisor: $(systemctl is-active supervisor)"
echo ""
echo -e "${YELLOW}下一步操作：${NC}"
echo "  1. 上传项目代码到 /home/ubuntu/civil/"
echo "  2. 配置 backend/.env 文件"
echo "  3. 运行 'cd /home/ubuntu/civil && chmod +x deploy/scripts/*.sh'"
echo "  4. 运行 './deploy/scripts/deploy.sh init' 进行首次部署"
echo "======================================"
echo -e "${NC}"
